<template>
  <Dialog title="填写信息" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="退款金额" prop="code">
        {{ (formData.actualPayment / 100).toFixed(2) }}
      </el-form-item>
      <el-form-item label="退款说明" prop="desc">
        <el-input v-model="formData.desc" type="textarea" placeholder="" />
      </el-form-item>
      <el-form-item label="图片" prop="url">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleRefundSuccess"
          :before-upload="beforeUpload"
          :headers="headers"
        >
          <img v-if="formData.url" :src="formData.url" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="操作人" prop="status">
        {{ formData.nickname }}
      </el-form-item>
      <el-form-item label="操作手机号" prop="status">
        {{ formData.phone }}
      </el-form-item>
      <el-form-item label="短信验证码" prop="checkCode">
        <el-row>
          <el-col><el-input v-model="formData.checkCode" placeholder="请输入" /></el-col>
          <el-col
            ><el-button :disabled="countdown > 0" @click="generateCaptcha">{{
              countdown > 0 ? countdown + '秒' : '发送验证码'
            }}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as OrderRefundApi from '@/api/meijia/order/refund'
import * as OrderApi from '@/api/meijia/order'
import * as UserApi from '@/api/system/user'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getAccessToken, getTenantId } from '@/utils/auth'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const url = import.meta.env.VITE_UPLOAD_URL
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  orderCode: undefined,
  url: undefined,
  desc: undefined,
  phone: undefined,
  checkCode: undefined,
  actualPayment: undefined,
  nickname: undefined
})
const formRules = reactive({
  desc: [{ required: true, message: '退款说明不能为空', trigger: 'blur' }],
  checkCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '图片不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const countdown = ref(0)
/** 打开弹窗 */
const open = async (code: string) => {
  dialogVisible.value = true
  resetForm()
  const data = await OrderApi.getOrderByCode(code)
  formData.value.orderCode = data.code
  formData.value.actualPayment = data.actualPayment
  const user = await UserApi.getSelf()
  formData.value.phone = user.phone
  formData.value.nickname = user.nickname
  // // 修改时，设置数据
  // if (id) {
  //   formLoading.value = true
  //   try {
  //     formData.value = await OrderRefundApi.getOrderRefund(id)
  //   } finally {
  //     formLoading.value = false
  //   }
  // }
}
const generateCaptcha = async () => {
  countdown.value = 59
  let timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
  UserApi.sendSmsCode({ phone: formData.value.phone })
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderRefundApi.OrderRefundVO
    await OrderRefundApi.refundOrderFlowList(data)
    message.success(t('common.createSuccess'))
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    dialogVisible.value = false
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    orderCode: undefined,
    status: undefined,
    remark: undefined,
    version: undefined
  }
  formRef.value?.resetFields()
}
const headers = ref({
  Authorization: 'Bearer ' + getAccessToken()
})
const handleRefundSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.url = response.data
}
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('上传照片不能超过5MB!')
    return false
  }
  return true
}
</script>
<style>
.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
</style>
<style scoped>
img {
  width: 150px;
}
</style>
